package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"user-profile/model/mysql"
	"user-profile/model/redisinit"
	"user-profile/pkg"

	"user-profile/userProfilerpc/internal/svc"
	"user-profile/userProfilerpc/userProfilerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAddLogic) UserAdd(in *userProfilerpc.UserAddRequest) (*userProfilerpc.UserAddResponse, error) {
	// todo: add your logic here and delete this line
	add := redisinit.Rdb.Get("sendSmsAdd" + in.Phone)
	if add.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	var findUser mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&findUser)
	if findUser.ID != 0 {
		return nil, fmt.Errorf("该账号已注册")
	}
	user := mysql.User{
		Model:    gorm.Model{ID: findUser.ID},
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&user)
	redisinit.Rdb.Del("sendSmsAdd" + in.Phone)
	return &userProfilerpc.UserAddResponse{
		Id: int64(user.ID),
	}, nil
}
